package cn.tedu._06article.controller;

import cn.tedu._06article.base.response.JsonResult;
import cn.tedu._06article.base.response.StatusCode;
import cn.tedu._06article.mapper.UserMapper;
import cn.tedu._06article.pojo.dto.UserArticleParam;
import cn.tedu._06article.pojo.dto.UserLoginParam;
import cn.tedu._06article.pojo.entity.Article;
import cn.tedu._06article.pojo.vo.ArticleVO;
import cn.tedu._06article.pojo.vo.UserVO;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@Slf4j
@Validated
@RestController
@Tag(name = "01-用户管理模块")
@RequestMapping("/v1/user")
public class UserController {

    @Autowired
    private UserMapper userMapper;

    /**
     * 1.登录功能
     */
    @PostMapping("/login")
    @Operation(summary = "登录功能")
    @ApiOperationSupport(order = 10)
    public JsonResult login(@RequestBody UserLoginParam userLoginParam, HttpSession session){
        log.debug("登录功能参数:" + userLoginParam);
        UserVO userVO = userMapper.selectByUsernameAndPassword(userLoginParam);
        if (userVO == null){
            return new JsonResult(StatusCode.USERNAME_PASSWORD_ERROR);
        }
        //登录成功,保存会话标识
        session.setAttribute("user", userVO);

        return JsonResult.ok(userVO);
    }

    /**
     * 2.发表文章功能
     */
    @PostMapping("/article")
    @Operation(summary = "发表文章功能")
    @ApiOperationSupport(order = 20)
    public JsonResult addArticle(@RequestBody @Validated UserArticleParam userArticleParam, HttpSession session){
        log.debug("发表文章功能参数:" + userArticleParam);
        UserVO userVO = (UserVO) session.getAttribute("user");
        //登录状态校验交由拦截器;
        Article article = new Article();
        BeanUtils.copyProperties(userArticleParam, article);
        article.setUserId(userVO.getId());
        log.debug("article:" + article);
        int i = userMapper.insertArticle(article);
        if (i > 0){
            return JsonResult.ok();
        }else {
            return new JsonResult(StatusCode.OPERATION_FAILED);
        }
    }

    /**
     * 3.查看指定文章
     */
    @GetMapping("/selectByArticleId")
    @Operation(summary = "查看指定文章")
    @ApiOperationSupport(order = 30)
    @Parameter(name = "id", description = "文章编号", required = true)
    public JsonResult selectArticle(@Range(min = 1L, max = 100L, message = "文章id必须在1-100之间") Long id){
        log.debug("查看指定文章参数:" + id);
        ArticleVO articleVO = userMapper.selectArticleById(id);

        return JsonResult.ok(articleVO);
    }
}










